<?php
Yii::import("application.website.*");
Yii::import("application.website.adapter.*");

class WebsiteUtil {
	
	/**
	 *  Gibt ein Array mit allen Parametern aus der URL zurück.
	 */
	public static function getParams($url) {
		$parts = explode('&', $url);
		$tmp = explode('?', $parts[0]);
		if (count($tmp) >= 2) $parts[0] = $tmp[1];
		$params = array();
		for($i = 0; $i < count($parts); ++$i) {
			$parts[$i] = explode("=", $parts[$i]);
			if(count($parts[$i]) == 2) $params[$parts[$i][0]] = $parts[$i][1];
		}
		return $params;
	}
	
	/**
	 * Gibt ein Array mit Statistiken zurück.
	 */
	public static function getStatistics() {
		$data = Yii::app()->db->createCommand("SELECT COUNT(*) FROM tbl_archive_url")->queryRow();
		$count = intval($data['COUNT(*)']);
		$data = Yii::app()->db->createCommand("SELECT COUNT(*) FROM tbl_archive_url WHERE fetched = 0")->queryRow();
		$unfetchedCount = intval($data['COUNT(*)']);
		$data = Yii::app()->db->createCommand("SELECT COUNT(*) FROM tbl_archive_board_category")->queryRow();
		$categoryCount = intval($data['COUNT(*)']);
		$data = Yii::app()->db->createCommand("SELECT COUNT(*) FROM tbl_archive_board_thread")->queryRow();
		$threadCount = intval($data['COUNT(*)']);
		$data = Yii::app()->db->createCommand("SELECT COUNT(*) FROM tbl_archive_board_post")->queryRow();
		$postCount = intval($data['COUNT(*)']);
		return array(
			'total' => $count,
			'unfetched' => $unfetchedCount,
			'categoryCount' => $categoryCount,
			'threadCount' => $threadCount,
			'postCount' => $postCount
		);
	}

	
	/**
	 * Fügt die URL hinzu, wenn es sie noch nicht gibt.
	 *  
	 */
	public static function addURL($url, $containsLinks, $board = null) {
		if ($url == null) return;
		$url = trim($url);
		if ($board != null && strpos("index", $url) == 0) $url = $board->base_url.$url;
		
		if ($containsLinks) $containsLinks = 1;
		else $containsLinks = 0;
		
		//remove session parameter
		$params = WebsiteUtil::getParams($url);
		if (array_key_exists("s", $params)) $url = str_replace("&s=", "", str_replace($params['s'], "", $url));
	//	var_dump($params);
		
		$archive = new ArchiveURL();
		$archive->url = $url;
		$archive->containsLinks = $containsLinks;
		if (!$archive->find("url = '".$url."'")) {
			$archive->setIsNewRecord(true);
			$archive->insert();
		}
	}
	
	/**
	 * Gibt das Board anhand der URL zurück. 
	 * 
	 * @return ArchiveBoard
	 */
	public static function getBoardByUrl($url) {
		$url = URLUtil::getBaseURL($url);
		$archive = new ArchiveBoard();
		return $archive->find("base_url = :url", array(":url" => $url));
	}
	
}
?>
